package link.chengguo.orangemall.modules.auth.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import link.chengguo.orangemall.annotation.SysLog;
import link.chengguo.orangemall.exception.BusinessMallException;
import link.chengguo.orangemall.exception.MemberNotExitException;
import link.chengguo.orangemall.modules.auth.dto.CheckPhoneDto;
import link.chengguo.orangemall.modules.auth.dto.BusinessUserDto;
import link.chengguo.orangemall.service.ums.RedisService;
import link.chengguo.orangemall.sys.service.ISysUserService;
import link.chengguo.orangemall.utils.CommonResult;
import link.chengguo.orangemall.utils.PhoneUtil;
import link.chengguo.orangemall.vo.Rediskey;
import link.chengguo.orangemall.vo.SmsCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName 用户认证模块
 * @Author: mxchen
 * @Date: 2020/9/19 15:49
 */
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(value = "认证模块", tags = "商城:认证", description = "认证")
public class AuthController {
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    private final ISysUserService sysUserService;
    private final RedisService redisService;

    @SysLog(MODULE = "auth", REMARK = "登录认证")
    @ApiOperation(value = "登录认证")
    @PostMapping(value = "/api/miniProgramBusinessLogin")
    public CommonResult login(@Validated @RequestBody BusinessUserDto umsAdminLoginParam) {

        String token = sysUserService.login(umsAdminLoginParam.getUsername(), umsAdminLoginParam.getPassword());
        if (token == null) {
            return new CommonResult().failed("用户名或密码错误");
        }
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.ok().success(tokenMap);

    }

    @SysLog(MODULE = "auth", REMARK = "修改密码")
    @ApiOperation(value = "修改密码")
    @PostMapping(value = "/api/editBusinessPassword")
    public CommonResult editBusinessPassword(@Validated @RequestBody BusinessUserDto businessUserDto){
        try{
            Boolean exit = sysUserService.checkPhoneExit(businessUserDto.getUsername());
            if(!exit){
                throw new MemberNotExitException("该账号不存在，请先申请入驻");
            }
            String checkCode = redisService.get(String.format(Rediskey.REDIS_KEY_PREFIX_AUTH_CODE, businessUserDto.getUsername()));
            if(StringUtils.isEmpty(checkCode)){
                throw new BusinessMallException("请先获取验证码");
            }
            if(!checkCode.equals(businessUserDto.getCode())){
                throw new BusinessMallException("验证码错误");
            }
            sysUserService.updatePassword(businessUserDto);

            return CommonResult.ok();
        }catch (BusinessMallException e){
            return CommonResult.error(e.getMessage());
        }

    }

    @SysLog(MODULE = "auth", REMARK = "发送短信验证码")
    @ApiOperation(value = "发送短信验证码")
    @PostMapping(value = "/api/businessPhoneCode")
    public CommonResult verify(
            @Validated @RequestBody CheckPhoneDto checkPhoneDto){
        try{
            if (!PhoneUtil.checkPhone(checkPhoneDto.getPhone())) {
                throw new IllegalArgumentException("手机号格式不正确");
            }
            Boolean exit = sysUserService.checkPhoneExit(checkPhoneDto.getPhone());
            if(!exit){
                throw new MemberNotExitException("该账号不存在，请先申请入驻");
            }
            SmsCode smsCode = sysUserService.generateCode(checkPhoneDto.getPhone());
            return CommonResult.ok().data("codeUUID",smsCode.getKey());
        }catch (Exception e){
            return CommonResult.error(e.getMessage());
        }

    }
}
